local delay = 20  -- in seconds
local new_timer = ngx.timer.at
local log = ngx.log
local ERR = ngx.ERR
local check
local fetcher = require('fetcher')
local dyupUtils = require('dyup_utils')

local action = function ()
  log(ERR, "action")
  local servers = fetcher.fetch()
  if servers then 
    dyupUtils.setServers(servers) 
  end

end
  --[[
  servers = {
    type1 = {
      '127.0.0.1:6001',
      '127.0.0.1:6002',
      '127.0.0.1:6003'
      },
    type2 = ... 
  }
  --]]

check = function(premature)
  log(ERR, "check")
  if not premature then

    action()
    -- do the health check or other routine work
    local ok, err = new_timer(delay, check)
    if not ok then
      log(ERR, "failed to create timer: ", err)
      return
    end
  end
end

-- new_timer(10, function () check(false) end)

local ok, err = new_timer(10, check)
if not ok then
  log(ERR, "failed to create timer: ", err)
  return
end
